package cn.sibu.plugin.authorize.activity;

import android.os.Bundle;

import com.alibaba.fastjson.JSON;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.ButterKnife;
import cn.sibu.plugin.authorize.R;
import cn.sibu.plugin.authorize.bean.UserInfo;
import cn.sibu.plugin.authorize.util.ConfigKeyName;
import cn.sibu.plugin.authorize.util.L;
import cn.sibu.plugin.authorize.util.ResponseCode;
import cn.sibu.plugin.authorize.util.SharedPreferencesUitls;
import core.dl.internal.DLIntent;


public class AutoLoginActivity extends BaseActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_login);
        ButterKnife.inject(this);
        checkToken();
    }
//    public void onDestroy(){
//        EventBus.getDefault().unregister(this);
//        super.onDestroy();
//    }
    /**
     * 检查token是否过期，时间7天，没过期自动登录，过期重新登录
     */
    private void checkToken() {
        String userInfoJson=SharedPreferencesUitls.getString(that,ConfigKeyName.USERINFO,null);
        try {
            UserInfo userInfo=JSON.parseObject(userInfoJson, UserInfo.class);
            if(userInfo!=null){
                //2015-05-26 17:52:13.0
//                userInfo.last_logintime;
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date lastLoginDate=sdf.parse(userInfo.last_logintime);
                long lastLoginTime=lastLoginDate.getTime();
                long day=(new Date().getTime()-lastLoginDate.getTime())/1000/60/60/24;
                L.e("登录间隔时间=" + day);
//                if(day>=0&&day<=7){
//                    gotoMainActivity(userInfo.groupid);
//                    return;
//                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        gotoLoginActivity();
    }
    private void gotoLoginActivity(){
        DLIntent intent = new DLIntent(getPackageName(), LoginActivity.class);
        intent.putExtra(ResponseCode.TOKENVOID, ResponseCode.TOKENVOID);
        startPluginActivity(intent);
        finish();
    }

    /**
     *
     * @param groupId
     */
    private void gotoMainActivity(String groupId){
        L.e("Main");
        DLIntent intent = new DLIntent(getPackageName(), MainActivity.class);
        intent.putExtra(ConfigKeyName.GROUPID, groupId);
        startPluginActivity(intent);
        finish();
    }
}
